package com.dolittle.test;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditView extends LinearLayout implements OnClickListener {

	private Context mContext;
	private TextView[] mTitle;
	private EditText[] mEdit;
	public static TextView mOutput;
	private Button mButtonEdit;
	private WordList mList;

	public EditView(Context context, WordList list) {
		super(context);
		mContext = context;
		mList = list;
		init();
	}

	private void init() {
		mTitle = new TextView[4];
		mEdit = new EditText[4];
		mOutput = new TextView(mContext);
		mButtonEdit = new Button(mContext);
		mButtonEdit.setOnClickListener(this);
		mButtonEdit.setId(1);

		for (int i = 0; i < 4; i++) {
			mTitle[i] = new TextView(mContext);
			mTitle[i].setId(i);
			mEdit[i] = new EditText(mContext);
			mEdit[i].setId(i);
		}
		mTitle[0].setHint("Swedish from:");
		mEdit[0].setHint("Write in Swedish here");
		mTitle[1].setHint("Spanish from:");
		mEdit[1].setHint("Write in Spanish here");

		mTitle[2].setHint("Swedish to:");
		mEdit[2].setHint("Write in Swedish here");
		mTitle[3].setHint("Spanish to:");
		mEdit[3].setHint("Write in Spanish here");

		mButtonEdit.setText("Edit word");
		initViews();

	}

	private void initViews() {
		setOrientation(VERTICAL);

		addView(mTitle[0]);
		addView(mEdit[0]);
		addView(mTitle[1]);
		addView(mEdit[1]);
		addView(mTitle[2]);
		addView(mEdit[2]);
		addView(mTitle[3]);
		addView(mEdit[3]);
		addView(mButtonEdit);
		addView(mOutput);
	}

	public void writeFile() {
		mList.writeFile();
	}

	public void setFrom(Word word) {
		mEdit[0].setText(word.getSwedish());
		mEdit[1].setText(word.getSpanish());
	}

	@Override
	public void onClick(View v) {
		if (v instanceof Button) {
			Button b = (Button) v;
			if (b.getId() == 1) {
				boolean edited = mList.editWord(mEdit[0].getText().toString(),
						mEdit[1].getText().toString(), mEdit[2].getText()
								.toString(), mEdit[3].getText().toString());
				if (edited) {
					mOutput.setText("Changed: "
							+ mEdit[0].getText().toString().toLowerCase()
							+ " = "
							+ mEdit[1].getText().toString().toLowerCase()
							+ " to "
							+ mEdit[2].getText().toString().toLowerCase()
							+ " = "
							+ mEdit[3].getText().toString().toLowerCase());
				} else {
					mOutput.setText("Word already exists.");
				}
			}
			mEdit[0].setText("");
			mEdit[1].setText("");
			mEdit[2].setText("");
			mEdit[3].setText("");
			writeFile();
		}
	}
}
